using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Nirvana.Common;
using UnityEngine;

namespace Nirvana.SkillEditor
{
    public class Skill : IPoolObject
    {
        private List<SkillActionBase> _watting;
        private List<SkillActionBase> _running;
        private float _curTime;

        /// <summary>
        /// 施法者
        /// </summary>
        private Entry _caster;
        /// <summary>
        /// 目标
        /// </summary>
        private Entry _target;
        /// <summary>
        /// 目标组
        /// </summary>
        private List<Entry> _targets;

        public Entry caster => _caster;
        
        public Entry target
        {
            get
            {
                if (_target != null)
                {
                    return _target;
                }

                if (_targets is {Count: > 0})
                {
                    return _targets[0];
                }

                return null;
            }
        }

        public List<Entry> targets => _targets;

        public void OnGet()
        {
            _curTime = 0;
            _watting = new List<SkillActionBase>();
            _running = new List<SkillActionBase>();
            _caster = null;
            _target = null;
            _targets = null;
        }

        public void OnRelease()
        {
            _curTime = 0;
            _watting = null;
            _running = null;
            _caster = null;
            _target = null;
            _targets = null;
        }

        public void Init(SkillSource source)
        {
            _watting.AddRange(source.actions);
        }

        public void Init(SkillSource source, Entry caster, Entry target)
        {
            _watting.AddRange(source.actions);
            _caster = caster;
            _target = target;
        }
        
        public void Init(SkillSource source, Entry caster, List<Entry> targets)
        {
            _watting.AddRange(source.actions);
            _caster = caster;
            _targets = targets;
        }

        public bool Running(float deltaTime)
        {
            var readyRunningActions = new List<SkillActionBase>();
            foreach (var action in _watting.Where(action => action.delay >= _curTime))
            {
                _running.Add(action);
                readyRunningActions.Add(action);
                action.Init(this);
            }

            var doneActions = _running.Where(action => !action.Running()).ToList();

            foreach (var action in readyRunningActions)
            {
                _watting.Remove(action);
            }
            
            foreach (var action in doneActions)
            {
                _running.Remove(action);
            }
            
            readyRunningActions.Clear();
            doneActions.Clear();

            _curTime += deltaTime;
            
            return _watting.Count != 0 || _running.Count != 0;
        }
    }
}
